package com.cheng.service.takedelivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cheng.dao.AreaDao;
import com.cheng.dao.FixedAreaRepository;
import com.cheng.dao.takedelivery.OrderDao;
import com.cheng.dao.takedelivery.WorkBillRepository;
import com.cheng.domain.base.Area;
import com.cheng.domain.base.Courier;
import com.cheng.domain.base.FixedArea;
import com.cheng.domain.base.SubArea;
import com.cheng.domain.constent.Constents;
import com.cheng.domain.takedelivery.Order;
import com.cheng.domain.takedelivery.WorkBill;
import com.cheng.service.takedelivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private AreaDao areaDao;
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private WorkBillRepository workBillRepository;
	
	//注入消息队列将短信和邮件交由消息队列发送
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
		
	@Override
	public void saveOrder(Order order) {
		order.setOrderNum(UUID.randomUUID().toString());
		order.setOrderTime(new Date());
		order.setStatus("1");
		//匹配发货区域
		Area sendArea = areaDao.findByProvinceAndCityAndDistrict(order.getSendArea().getProvince(),order.getSendArea().getCity(),order.getSendArea().getDistrict());
		//匹配收回哦区域
		Area recArea = areaDao.findByProvinceAndCityAndDistrict(order.getSendArea().getProvince(),order.getSendArea().getCity(),order.getSendArea().getDistrict());
		order.setSendArea(sendArea);
		order.setRecArea(recArea);
System.out.println(order.getSendAddress());
		//获取客户匹配的定区
		String fixedAreaId = WebClient.create(Constents.CRM_MANAGEMENT_URL+"/crm_management/service/customerService/getfixedareabyaddress?address="+order.getSendAddress()+"&id="+order.getCustomer_id()).accept(MediaType.APPLICATION_JSON).get(String.class);
System.out.println(fixedAreaId);
		if (fixedAreaId != null) {
			FixedArea fixedarea = fixedAreaRepository.findOne(fixedAreaId);
			//获取定区关联的快递员
			Set<Courier> couriers = fixedarea.getCouriers();
			Iterator<Courier> iterator = couriers.iterator();
			if (iterator.hasNext()) {
				Courier courier = iterator.next();
System.out.println("自动分单成功");
				order.setCourier(courier);
				order.setOrderNum(UUID.randomUUID().toString());
				//保存订单
				saveOrder(order, courier);
				//发送短信，保存工单
				saveWorkBill(order);
				return;
			}
		}
		//通过分区关键字和辅助关键字实现自动分单
		Set<SubArea> subareas = sendArea.getSubareas();
		if(subareas.size() > 0){
			for (SubArea subArea : subareas) {
				if (order.getSendAddress().contains(subArea.getKeyWords()) || order.getSendAddress().contains(subArea.getAssistKeyWords())) {
					FixedArea  fixedArea = subArea.getFixedArea();
					//获取定区关联的快递员
					Set<Courier> couriers = fixedArea.getCouriers();
					Iterator<Courier> iterator = couriers.iterator();
					if (iterator.hasNext()) {
						Courier courier = iterator.next();
System.out.println("自动分单成功");
						order.setCourier(courier);
						
						//保存订单
						saveOrder(order, courier);
						//发送短信，保存工单
						saveWorkBill(order);
						return;
					}
				}
			}
		}
		order.setOrderType("2");
		orderDao.save(order);
System.out.println("自动分单失败，进入人工分单");
	}

	//自动分单成功，生成工单
	private void saveWorkBill(Order order) {
		//生成工单
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		final String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber); // 短信序号
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		//保存工单
		workBillRepository.save(workBill);
		//发送短信
		jmsTemplate.send("bos_telephonecode", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier()
						.getTelephone());
				mapMessage.setString(
						"mesg",
						"短信序号：" + order.getOrderNum() + ",取件地址：" + order.getSendAddress()
								+ ",联系人:" + order.getSendName() + ",手机:"
								+ order.getSendMobile() + "，快递员捎话："
								+ order.getSendMobileMsg());
				return mapMessage;
			}
		});
		// 修改工单状态
		workBill.setPickstate("已通知");
	}
	
	
	// 自动分单保存
		private void saveOrder(Order order, Courier courier) {
			// 将快递员关联订单上
			order.setCourier(courier);
			// 设置自动分单
			order.setOrderType("1");
			// 保存订单
			orderDao.save(order);
		}

		@Override
		public Order findOrderByOrderNum(String orderNum) {
			return orderDao.findByOrderNum(orderNum);
		}
	
}
